#!/bin/bash
set -e

cd $(dirname $0)/..

: ${BUILD:=$(pwd)/build}
: ${DIST:=$(pwd)/dist}

busybox_install()
{
    local build=$1
    local conf=$2
    local bbconf=$3
    echo "SO $build, $conf, $bbconf"

    mkdir -p ${BUILD}
    cd ${BUILD}

    local buildroot=$(ls -1 ${ARTIFACTS}/${TARBALL})

    if [ ! -e "${buildroot}" ]; then
        echo "Failed to find busybox archive, found : ${buildroot}" 1>&2
        return 1
    else
        buildroot=$(basename $buildroot)
    fi

    DIR=${buildroot/.tar.*//}
    mkdir -p ${DIR}
    tar xf ${ARTIFACTS}/${buildroot} -C ${DIR} --strip-components=1
    cd ${DIR}

    cp $conf .config
    if [ -n "$bbconf" ]; then
        cp $bbconf package/busybox/
    fi
    export HOME=${BUILD}
    if [ "$build" == "config" ]; then
        make menuconfig
    else
        make oldconfig
    fi
    cp .config ${DIST}/artifacts/$(basename $conf)

    if [ "$build" == "config" ]; then
        make busybox-menuconfig
        cp output/build/busybox-*/.config ${DIST}/artifacts/$(basename $bbconf)
        cp output/build/busybox-*/.config ${target}.$(basename $bbconf)
    fi


    if [ "$build" == "build" ]; then
        make
    fi
}

busybox_install "$1" "$2" "$3"
